import React, { FC, useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'
import { Form, Input, Row, Button, message, Col } from 'antd'
import { UserOutlined, UnlockOutlined, EyeInvisibleOutlined, EyeTwoTone, SafetyCertificateOutlined } from '@ant-design/icons'
import { RouteComponentProps } from 'react-router'
import { observer } from 'mobx-react'
import { LoginInfo } from '@/interface/login'
import { useStore } from '@/store'
import { fetchLoginImg } from '@/api/system/user'
import headImg from '@/assets/images/logo.svg'

import './login.scss'

const Login: FC<RouteComponentProps> = () => {
  const history = useHistory()
  const { userStore } = useStore()
  const [state, setState] = useState({ imgBase64: '', imgId: '' })
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm<{ username: string; password: string }>()
  const rules = {
    name: [
      { required: true, message: '请填写用户名', trigger: 'blur' },
      { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请填写密码', trigger: 'blur' },
      { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
    ],
    imgCode: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
  }

  // 获取图片验证码
  const handleCaptcha = () => {
    fetchLoginImg().then((res) => {
      setState(res)
    })
  }

  useEffect(() => {
    handleCaptcha()
  }, [])

  const { validateFields } = form
  const onFinish = () => {
    validateFields().then((values: LoginInfo) => {
      userStore.login(Object.assign(values, { imgId: state.imgId })).then((res) => {
        if (res.code) {
          setLoading(false)
          message.success(res.message)

          if (res.message === '验证码过期') {
            handleCaptcha()
          }
        } else {
          history.push('/')

          // 延迟 1 秒显示欢迎信息
          setTimeout(() => {
            message.success('Hi, 欢迎回来')
          }, 1000)
        }
      }).catch(() => {
        setLoading(false)
      })
      setLoading(true)
    })
  }

  return (
    <div className="app-login">
      <Form
        className="app-login-form"
        layout="horizontal"
        form={form}
        onFinish={onFinish}
      >
        <h1>
          <img src={headImg} alt="logo" className="logo" />
          <span>工作基建平台</span>
        </h1>
        <Form.Item name="name" rules={rules.name} hasFeedback>
          <Input size="large" autoComplete="off" prefix={<UserOutlined />} placeholder="用户名" />
        </Form.Item>
        <Form.Item name="password" rules={rules.password} hasFeedback>
          <Input.Password autoComplete="off" size="large" prefix={<UnlockOutlined />} placeholder="密码" iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)} />
        </Form.Item>
        <Form.Item className="imgcode-item">
          <Row gutter={8}>
            <Col span={12}>
              <Form.Item name="imgCode" rules={rules.imgCode}>
                <Input className="captch-input" size="large" autoComplete="off" prefix={<SafetyCertificateOutlined />} placeholder="图形验证码" />
              </Form.Item>
            </Col>
            <Col span={12} className="captcha-col">
              <span onClick={handleCaptcha}><img className="captcha" src={state.imgBase64} alt="图形验证码" /></span>
            </Col>
          </Row>
        </Form.Item>
        <Row>
          <Button block size="large" type="primary" htmlType="submit" loading={loading}>登录</Button>
        </Row>
      </Form>
    </div>
  )
}

export default observer(Login)
